import api from '../../../api/index';
import dayjs from '../../../plugin/dayjs/index';
import daysbefore from '../../../plugin/daysbefore';
import * as echarts from '../../../components/ec-canvas/echarts';
import bleUtils from '../../utils/bluetooth'

//全局声明chart
var seriesDataArr = [];
var timeArr = [];
var chart = null;

// 时间格式化
function formatTime(date = new Date()) {
	return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
}
function formatTime2(date = new Date()) {
	return dayjs(date).format('YYYY-MM-DD');
}
Page({
	/**
   * 页面的初始数据
   */
	data: {
		showDialogdevice: false,
		inputshow: false,
		inputlist: [ { unit: '血糖', value: '', text: '请输入血糖', key: 'XYZBXY001008' }, { unit: '尿酸', value: '', text: '请输入尿酸', key: 'lk1681869139108' }, { unit: '血酮', value: '', text: '请输入血酮', key: 'lk1681869139105' } ],
		c_val: 80,
		shebeiicon: 'http://lk-webfont.oss-cn-beijing.aliyuncs.com/redstart/%E4%B8%89%E5%90%88%E4%B8%80.png',
		fasleshebeiicon: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/sportsAdministration/gantanhao.png',
		FastingBloodSugarValueLast: '--',
    UricAcidValueLast: '--',
    BloodKetoneValueLast: '--',
    linedata: null,
    show: false,
    ec: {
      // 初始化图表
      onInit:  (canvas, width, height) => {
        //初始化echarts元素，绑定到全局变量，方便更改数据
        chart = echarts.init(canvas, null, {
          width: width,
          height: height
        });
        canvas.setChart(chart);
        return chart;
      }
    },
		bindDeviceId: null,
		UricAcidValue: '--',
		FastingBloodSugarValue: '--',
		BloodKetoneValue: '--',
		showDialog: false,
		bindDeviceTextInfo: '',
	},

	/**
   * 生命周期函数--监听页面加载
   */
	onLoad(options) {
		// this.drawProgress()
		this.gethistrorylist(); //查看历史数据
    this.getloadlist(); //查询当前最新数据
		this.doInitBlue()
  },
  gohistorypage() {
	wx.navigateTo({
	 url: `/three-in-one/pages/history/index`,
	  })
   },
	gethistrorylist() {
		api
			.post('/api/hxhealth/exams/records', {
				data: {
					everyday: true,
					itemcode: '',
					typecode: 'threeinoneequip',
				},
				head: {
					firstresult: 0,
					maxresults: 1000,
					bodytype: 'flat',
				}
			})
			.then((res) => {
				// console.log(res);
				console.log('----历史数据----', res);
				if (res.length > 0) {
					const jsonData = res;
					// 提取数据的数组
					const values1 = [];
					const values2 = [];
					const values3 = [];
					const times = [];

					// 遍历 body 数组
					jsonData.forEach((entry) => {
						// 遍历 devices 数组
						entry.devices.forEach((device) => {
							console.log(device);
							// 找到 code 为 "XYZBXY001008" 的项
							const item1 = device.items.find((item) => item.code === 'XYZBXY001008');
							const item2 = device.items.find((item) => item.code === 'lk1681869139108');
							const item3 = device.items.find((item) => item.code === 'lk1681869139105');
							times.push(entry.time.slice(0, 10).replace(/-/g, '/'));

							// 如果找到了，将 value 和 time 添加到相应的数组中
							if (item1) {
								values1.push(Number(item1.value)); // 将值转换为数字类型
							} else {
								values1.push(null); 
							}
							if (item2) {
								values2.push(Number(item2.value)); // 将值转换为数字类型
							} else {
								values2.push(null); 
							}
							if (item3) {
								values3.push(Number(item3.value)); // 将值转换为数字类型
							} else {
								values3.push(null); 
							}
						});
					});
					const linedata = {
						values1,
						values2,
						values3,
						times
					};
          console.log(linedata, 'linedata');
          this.setData({
            linedata
          });
          // 模拟获取接口数据
    setTimeout(() => {
      this.getEchartData(linedata)
    }, 1000);
				} else {
					const linedata = {
						values: [],
						times: this.getWeekDays()
					};
					this.setData({
						linedata
					});
					// 模拟获取接口数据
					setTimeout(() => {
						this.getEchartData(linedata);
					}, 1000);
				}
			});
	},
	getWeekDays() {
		let dates = []
		for (var i = 365; i >= 0; i--) {
			var currentDate = new Date();
			currentDate.setDate(currentDate.getDate() - i);
			var month = ("0" + (currentDate.getMonth() + 1)).slice(-2);
			var day = ("0" + currentDate.getDate()).slice(-2);
			var formattedDate = month + "/" + day;
			dates.push(formattedDate);
		}
		return dates
	},
	getloadlist() {
		// 整体列表查询
		api
			.post('/api/exams/lastvalues', {
				data: {
					devkind: 'threeinoneequip',
					devmode: '',
					itemcode: '',
					typecode: '',
					unionuser: true
				}
			})
			.then((res) => {
				// console.log(res);
				this.setData({
					newtime: res[0].examtime
				});
				console.log('----最新数据----', res);
				const array = res;
				for (let y = 0; y < array.length; y++) {
					if (array[y].code == 'XYZBXY001008') {
						this.setData({
							FastingBloodSugarValueLast: Number(array[y].value).toFixed(2)
						});
					}
					if (array[y].code == 'lk1681869139108') {
						this.setData({
							UricAcidValueLast: Number(array[y].value).toFixed(2)
						});
          }
          if (array[y].code == 'lk1681869139105') {
						this.setData({
							BloodKetoneValueLast: Number(array[y].value).toFixed(2)
						});
					}
				}
			});
	},
	savedevices() {
		const list = []
		this.data.inputlist.forEach(item => {
			if (item.value) {
				const obj = {
					code: item.key,
					checkDate: null,
					level: null,
					value: item.value,
					deviceBrand: '',
					deviceNo: ''
				}
				list.push(obj)
			}
		})
		console.log(list, '2222');
		let data = {
			name: '三合一监测',
			time: formatTime(),
			typecode: 'threeinoneequip',
			typename: '三合一监测',
			devices: [
				{
					name: '三合一监测',
					kind: 'threeinoneequip',
					items: list
				}
			]
		};
		// 整体列表查询
		api
			.post('/api/hxhealth/exams/save', {
				data
			})
			.then((res) => {
				// console.log(res);
				console.log('----保存录入----', res);
				this.getloadlist();
				this.gethistrorylist()
				this.closesaveNickname();
				wx.showToast({
					icon: 'none',
					title: '保存成功'
				});
			})
			.catch((e) => {
				console.log(e);
				wx.showToast({
					icon: 'none',
					title: e.faultstring ? e.faultstring : '保存失败'
				});
			});
	},
	openNickname() {
		this.setData({
			inputshow: true
		});
	},
	closesaveNickname() {
		this.setData({
			inputshow: false
		});
	},
	userNameInput1(e) {
		console.log(e.detail.value);
		this.setData({
			'inputlist[0].value': e.detail.value
		});
	},
	userNameInput2(e) {
		console.log(e.detail.value);
		this.setData({
			'inputlist[1].value': e.detail.value
		});
  },
  userNameInput3(e) {
		console.log(e.detail.value);
		this.setData({
			'inputlist[2].value': e.detail.value
		});
	},
	saveNickname() {
		console.log(this.data.inputlist);
		let cansave = true
		this.data.inputlist.forEach(item => {
			if(!item.value) {
				wx.showToast({
					title: '请输入数值',
					icon: 'none',
					duration: 2000
				})
				cansave = false
				return
			}
			if(!/^[0-9]+(\.[0-9]+)?$/.test(Number(item.value))) {
				wx.showToast({
					title: '请输入最多两位小数的数值',
					icon: 'none',
					duration: 2000
				})
				cansave = false
				return
			}
		})
		if(cansave) {
			this.savedevices();
		}
	},
	modal_click_Hidden() {
		this.setData({
			inputshow: false
		});
  },
    // 绘制图表
    runColumncCanva() {
      var option = {
        title: {
          // text: '次/分', 
          textStyle: {
              fontSize: 9,
              color: '#666666'
          }
      },
        color: ['#FF0000', '#37A2DA', '#800080'],
        legend: {
          data: ['血糖', '尿酸', '血酮'],
          icon: 'circle',
          left: 0,
          itemWidth: 9,
          // itemStyle: {
          //     color: '#5BBF70'
          // },
          textStyle: {
              color: '#333333',
              fontSize: 20
          }
      },
        grid: {
          left: '0%',
          right: '5%',
          bottom: 0,
          top: '15%',
          containLabel: true,
          show: true
      },
        
        tooltip: {
          show: true,
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: timeArr,
          axisLabel:{
					fontSize: 16,
            rotate:45,//倾斜度 -90 至 90 默认为0
          }
        },
        yAxis: {
          type: 'value',
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          },
		  axisLabel: {
			  fontSize: 16
		  }
        },
        series: seriesDataArr
      };
      //这里一定要做个charts是否存在的判断，因为万一ec那里没有初始化，这里就会报错
      if (chart) {
        chart.setOption(option);
        this.setData({
          show: true
        });
      }
    },
    getEchartData (linedata) {
      seriesDataArr = [{
        name: '血糖',
        type: 'line',
        smooth: true,
        data: linedata.values1,
				connectNulls: true
      },{
        name: '尿酸',
        type: 'line',
        smooth: true,
        data: linedata.values2,
				connectNulls: true
      },{
        name: '血酮',
        type: 'line',
        smooth: true,
        data: linedata.values3,
				connectNulls: true
      }]
        timeArr = linedata.times
        this.runColumncCanva()
    },
	// 蓝牙初始化
	doInitBlue() {
		bleUtils.initBlueTooth().then((res) => {
			this.get()
		  this.doGetBluetoothAdapterState()
		}).catch(error => {
			this.setData({
        bindDeviceTextInfo: '蓝牙未开启，请开启蓝牙'
      })
      this.setData({
        showDialog: true
      })
		})
	},
	  // 获取蓝牙适配器状态
	doGetBluetoothAdapterState() {
		bleUtils.getBluetoothAdapterState().then((res) => {
		})
	},
	//开始搜索蓝牙设备
  doStartSearchBlueTooth() {
    bleUtils.startSearchBlueTooth().then((res) => {
      console.log(res, '搜索设备成功')
      this.doOnBluetoothDeviceFound()
    })
  },
	// 监听搜素到新的蓝牙设备
  doOnBluetoothDeviceFound() {
    bleUtils.onBluetoothDeviceFound().then((res) => {
      console.log(res, '监听搜素到新的蓝牙设备成功')
			const filterValue = res.filter(item => item.name.indexOf('1311') > -1)
			if(filterValue.length > 0) {
				this.setData({
					bindDeviceId: filterValue[0].deviceId
				})
				this.setData({
					bindDeviceTextInfo: '搜索到设备，正在链接设备'
				})
				// 搜索到可用的蓝牙设备，停止搜索
				bleUtils.stopSearchBlueTooth()
				this.bindEquipment()
			} else {
				//没有搜索到可用设备，重新搜索
				console.log('没有搜索到可用设备，重新搜索')
				// this.doStartSearchBlueTooth()
				this.setData({
					bindDeviceTextInfo: '没有搜索到对应的蓝牙设备，请重新搜索'
				})
				setTimeout(() => {
					this.setData({
						showDialog: false
					})
				}, 1500);
			}
    })
  },
	async get() {
		try {
		  const res = await api.post('/api/user/storage/get', {
			data: {
			  'key': 'devicelist'
			}
		  })
		  if(res[0].value) {
				var array = JSON.parse(res[0].value)
				const listValue = array.filter(item => item.name === 'threeinone')
				if(listValue.length > 0) {
					this.bindEquipment(listValue[0].devicelist[0].deviceId)
				} else {
					this.setData({
					 showDialogdevice: true
					}) 
					 }
		  } else {
			this.setData({
			 showDialogdevice: true
			}) 
			 }
		} catch (e) {
		  console.log('get->', e)
		  return null
		}
	},
	// 连接蓝牙设备
  bindEquipment(deviceId) {
		this.setData({
			bindDeviceId: deviceId
		})
		this.setData({
			bindDeviceTextInfo: '连接设备中...'
		})
		this.setData({
			showDialog: true
		})
    bleUtils.createBLEConnection(this.data.bindDeviceId).then((res) => {
			this.setData({
				bindDeviceTextInfo: '设备链接成功,正在测量'
			})
      this.doGetBLEDeviceServices()
    }).catch(err => {
      console.log(err, '连接设备失败')
      this.doGetBLEDeviceServices()
    })
  },
  // 获取蓝牙设备特征值
  doGetBLEDeviceServices() {
    bleUtils.getBLEDeviceServices(this.data.bindDeviceId).then((res) => {
      console.log(res, '获取到设备发送过来的数据成功AAAAAAAAAAAA')
			if (res.success) {
				this.setData({
					bindDeviceTextInfo: '测量成功'
				})
				setTimeout(() => {
					this.setData({
						showDialog: false
					})
				}, 500);
				if(res.type === 'niaosuan') {
					this.setData({
						UricAcidValue: Number(res.value).toFixed(2),
					})
					this.setData({
						'inputlist[1].value': Number(res.value).toFixed(2)
					});
				} else if(res.type === 'xuetang') {
					this.setData({
						FastingBloodSugarValue: Number(res.value).toFixed(2),
					})
					this.setData({
						'inputlist[0].value': Number(res.value).toFixed(2)
					});
				} else if (res.type === 'xuetong') {
					this.setData({
						BloodKetoneValue: Number(res.value).toFixed(2),
					})
					this.setData({
						'inputlist[2].value': Number(res.value).toFixed(2)
					});
				}
				this.savedevices()
			} else {
				this.setData({
					bindDeviceTextInfo: '测量出错'
				})
				setTimeout(() => {
					this.setData({
						showDialog: false
					})
				}, 500);
			}
    })
  },
	onCancel() {
		this.setData({
			showDialog: false,
		})
		// 停止搜索
		bleUtils.stopSearchBlueTooth()
	},
	// 链接设备
	goBindEq() {
		wx.navigateTo({
			url: '/three-in-one/pages/measurement/index'
		});
	},

	/**
   * 生命周期函数--监听页面初次渲染完成
   */
	onReady: function() {
    
	},

	/**
   * 生命周期函数--监听页面显示
   */
	onShow() {},

	/**
   * 生命周期函数--监听页面隐藏
   */
	onHide() {},

	/**
   * 生命周期函数--监听页面卸载
   */
	onUnload() {
		this.closeBLE(this.data.bindDeviceId)
	},

	/**
   * 页面相关事件处理函数--监听用户下拉动作
   */
	onPullDownRefresh() {},

	/**
   * 页面上拉触底事件的处理函数
   */
	onReachBottom() {},

	/**
   * 用户点击右上角分享
   */
	onShareAppMessage() {}
});
